package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.security.interfaces.DSAPrivateKey;
import java.security.interfaces.DSAPublicKey;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

import util.RequestUtil;
import util.SamlException;
import util.Util;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private final String samlResponseTemplateFile = "SamlResponseTemplate.xml";
	private static final String domainName = "psosamldemo.net";

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public LoginServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse
	 *      response)
	 *//*
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String username = (String) request.getParameter("username");
		String password = (String) request.getParameter("password");

		HttpSession session = request.getSession();

		String processType = (String) session.getAttribute("processType");

		if (("user@identityProvider.com".equals(username) && "password"
				.equals(password))) {

			session.setAttribute("status", "validated");
			session.setAttribute("user", username);

			if ("sso".equals(processType)) {
				request.getRequestDispatcher("ProcessSAMLResponseServlet")
						.forward(request, response);
			} else {
				request.getRequestDispatcher("main.jsp").forward(request,
						response);
			}

		} else {
			request.setAttribute("errorMessage",
					"No validated user, please login");
			request.getRequestDispatcher("index.jsp")
					.forward(request, response);
		}

		
		 * if ((status != null && "validated".equals(status)) ||
		 * ("user@identityProvider.com".equals(username) && "password"
		 * .equals(password))) {
		 * 
		 * if (!(status != null && "validated".equals(status))) {
		 * session.setAttribute("user", username);
		 * session.setAttribute("status", "validated"); }
		 * 
		 * String user = (String) session.getAttribute("user"); String
		 * processType = (String) session.getAttribute("processType"); String
		 * acsURL = (String) session.getAttribute("acsURL"); String requestId =
		 * (String) session.getAttribute("requestId"); String issueInstant =
		 * (String) session.getAttribute("issueInstant");
		 * 
		 * if ("sso".equals(processType)) { String notBefore =
		 * Util.getNotBeforeDateAndTime(); String notOnOrAfter =
		 * Util.getNotOnOrAfterDateAndTime(); try { String responseXmlString =
		 * createSamlResponse(user, notBefore, notOnOrAfter, requestId, acsURL);
		 * 
		 * String publicKeyFilePath = getServletContext().getRealPath(
		 * "./keys/DSAPublicKey01.key"); String privateKeyFilePath =
		 * getServletContext() .getRealPath("./keys/DSAPrivateKey01.key");
		 * 
		 * DSAPublicKey publicKey = (DSAPublicKey) Util.getPublicKey(
		 * publicKeyFilePath, "DSA"); DSAPrivateKey privateKey = (DSAPrivateKey)
		 * Util .getPrivateKey(privateKeyFilePath, "DSA");
		 * 
		 * String signedSamlResponse = ProcessResponseServlet
		 * .signResponse(responseXmlString, publicKey, privateKey);
		 * 
		 * // String //
		 * encodeResponse=RequestUtil.encodeMessage(signedSamlResponse);
		 * 
		 * // String //
		 * decodeReponse=ProcessResponseServlet.decodeAuthnRequestXML
		 * (encodeResponse);
		 * 
		 * PrintWriter out = response.getWriter();
		 * 
		 * out.println(
		 * "<html><body onload='document.forms[0].submit();'><form style='display:none' method='post' action='"
		 * + acsURL + "'>"); out.println(
		 * "<input name='test' value='aa'><input name='SAMLResponse' value='" +
		 * responseXmlString + "'></form></body></html>'");
		 * 
		 * } catch (SamlException e) { e.printStackTrace(); } } else {
		 * request.getRequestDispatcher("main.jsp").forward(request, response);
		 * } } else { request.setAttribute("errorMessage",
		 * "No validated user, please login");
		 * request.getRequestDispatcher("index.jsp") .forward(request,
		 * response); }
		 

	}*/

	/*
	 * Generates a SAML response XML by replacing the specified username on the
	 * SAML response template file. Returns the String format of the XML file.
	 */
	private String createSamlResponse(String authenticatedUser,
			String notBefore, String notOnOrAfter, String requestId,
			String acsURL) throws SamlException {
		String filepath = getServletContext().getRealPath(
				"templates/" + samlResponseTemplateFile);
		String samlResponse = Util.readFileContents(filepath);
		samlResponse = samlResponse.replace("<USERNAME_STRING>",
				authenticatedUser);
		samlResponse = samlResponse.replace("<RESPONSE_ID>", Util.createID());
		samlResponse = samlResponse.replace("<ISSUE_INSTANT>", Util
				.getDateAndTime());
		samlResponse = samlResponse.replace("<AUTHN_INSTANT>", Util
				.getDateAndTime());
		samlResponse = samlResponse.replace("<NOT_BEFORE>", notBefore);
		samlResponse = samlResponse.replace("<NOT_ON_OR_AFTER>", notOnOrAfter);
		samlResponse = samlResponse.replace("<ASSERTION_ID>", Util.createID());
		samlResponse = samlResponse.replace("<REQUEST_ID>", requestId);
		samlResponse = samlResponse.replace("<ACS_URL>", acsURL);
		return samlResponse;

	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();

		session.removeAttribute("status");
		session.removeAttribute("user");
		
		String logoutType=(String)request.getParameter("logoutType");

		if("global".equals(logoutType)){
			
			String spIndexPage="http://localhost:8088/serviceProvider";
			response.sendRedirect(spIndexPage);
		}
		
		request.getRequestDispatcher("index.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		String username = (String) request.getParameter("username");
		String password = (String) request.getParameter("password");

		HttpSession session = request.getSession();

		String processType = (String) session.getAttribute("processType");

		if (("user@identityProvider.com".equals(username) && "password"
				.equals(password))) {

			session.setAttribute("status", "validated");
			session.setAttribute("user", username);

			if ("sso".equals(processType)) {
				request.getRequestDispatcher("ProcessSAMLResponseServlet")
						.forward(request, response);
			} else {
				request.getRequestDispatcher("main.jsp").forward(request,
						response);
			}

		} else {
			request.setAttribute("errorMessage",
					"No validated user, please login");
			request.getRequestDispatcher("index.jsp")
					.forward(request, response);
		}
	}

}
